﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Web;
using Saber.Infrastructure.Logger;


namespace Saber.Plugin.OpenCMD
{
    public class Main : IPlugin, IContextMenu
    {

        private static PluginMetadata metadata;

        private PluginInitContext context;
        private static List<SystemWindow> openingWindows = new List<SystemWindow>();

        static Main()
        {
            metadata = new PluginMetadata();
            metadata.ID = "D2D2C23B084D411DB99EE0C79D6C2A6C";
            metadata.Name = "快速命令行";
            metadata.Description = "在资源管理器打开的路径下启动Windows命令提示符";
            metadata.ActionKeyword = "op";
            metadata.IcoPath = "Images\\opencmd.png";

            // use to auto load Interop.SHDocVw.dll from resources
            // only copy to plugin folder can not load correctly
            //AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
        }

        public List<Result> Query(Query query)
        {
            //var list = new List<Result>();

            //SystemWindow win = null;
            GetOpeningWindows();
            return openingWindows.AsParallel().Select(win =>
            {
                foreach (SHDocVw.InternetExplorer window in new SHDocVw.ShellWindowsClass())
                {
                    if (win.HWnd == (IntPtr)window.HWND)
                    {
                        var filename = Path.GetFileNameWithoutExtension(window.FullName).ToLower();
                        if (filename.ToLowerInvariant() == "explorer")
                        {
                            if (!window.LocationURL.ToLower().Contains("file:"))
                                continue;

                            var path = window.LocationURL.Replace("file:///", "");
                            path = HttpUtility.UrlDecode(path);
                            if (!Directory.Exists(path))
                                continue;

                            return new Result()
                            {
                                IcoPath = "Images\\opencmd.png",
                                Title = path,
                                SubTitle = "在当前打开的资源管理器路径中启动命令行",
                                Action = (c) =>
                                {
                                    StartShell(path);
                                    return true;
                                }
                            };

                        }
                    }
                }
                return null;

            }).Where(win => null != win).ToList();
        }

        public void Init(PluginInitContext context)
        {
            this.context = context;
        }

        private static void StartShell(string path)
        {
            path = HttpUtility.UrlDecode(path);



            Process.Start(new ProcessStartInfo()
            {
                FileName = "cmd",
                WorkingDirectory = path
            });

        }

        private static void StartShellAs(string path)
        {
            path = HttpUtility.UrlDecode(path);

            Process.Start(new ProcessStartInfo()
            {
                FileName = "cmd",
                Arguments = "/K \" CD /D " + path + "\"",
                WorkingDirectory = path,
                Verb = "runas"
            });

        }

        private static void GetOpeningWindows()
        {
            openingWindows.Clear();
            WinApi.EnumWindowsProc callback = EnumWindows;
            WinApi.EnumWindows(callback, 0);
        }

        private static bool EnumWindows(IntPtr hWnd, int lParam)
        {
            if (!WinApi.IsWindowVisible(hWnd))
                return true;

            var title = new StringBuilder(256);
            WinApi.GetWindowText(hWnd, title, 256);

            if (string.IsNullOrEmpty(title.ToString()))
            {
                return true;
            }

            if (title.Length != 0 || (title.Length == 0 & hWnd != WinApi.statusbar))
            {
                var window = new SystemWindow(hWnd);
                if (window.IsAltTabWindow() && !window.IsTopmostWindow())
                {
                    openingWindows.Add(window);
                }
            }

            return true;
        }

        //public static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        //{
        //    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");

        //    dllName = dllName.Replace(".", "_");

        //    if (dllName.EndsWith("_resources")) return null;

        //    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(typeof(Main).Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

        //    byte[] bytes = (byte[])rm.GetObject(dllName);

        //    Log.Info("Saber.Plugin.OpenCMD 加载资源：" + dllName + " Length:" + bytes.Length);

        //    return System.Reflection.Assembly.Load(bytes);
        //}

        public PluginMetadata Metadata()
        {
            return metadata;
        }

        public List<Result> LoadContextMenus(Result selectedResult)
        {
            var contextMenus = new List<Result>
            {
                new Result
                {
                    Title = "以管理员身份运行",
                    Action = _ =>
                    {
                        StartShellAs(selectedResult.Title);
                        return true;
                    },
                    IcoPath = "Images/opencmd.png"
                }
            };
            return contextMenus;
        }
    }
}
